<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          v-for="item in AllTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请输入SPU描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!-- v-model:用于展示默认图片 
           action:上传图片的接口地址 
           list-type:上传图片的样式
      -->
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        :headers="headers"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <!-- 展示销售属性的表单 -->
      <el-select
        style="width: 70%"
        :placeholder="
          unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : ''
        "
        v-model="saleAttrIdAndName"
      >
        <el-option
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        type="primary"
        icon="Plus"
        :disabled="!saleAttrIdAndName"
        @click="addSaleAttr"
        >添加属性</el-button
      >
      <!-- 展示销售属性与属性值 -->
      <el-table border style="margin: 10px 0" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #="{ row, $index }">
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="row.spuId"
              closable
              style="margin: 0 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
              v-if="row.flag === true"
              v-model="row.saleAttrValue"
              @blur="toLook(row)"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <!-- 保存和取消按钮 -->
    <el-form-item>
      <el-button
        type="primary"
        @click="save"
        :disabled="saleAttr.length ? false : true"
        >保存</el-button
      >
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
// el-upload 上传 http 请求头，携带 Token
// 引入用户相关的仓库
import useUserStore from "@/store/modules/user";
// 获取用户相关的小仓库：获取仓库内部token，登录成功以后携带给服务器
const userStore = useUserStore();
const headers = { Token: userStore.token };
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import type {
  SpuData,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  SaleAttr,
  HasSaleAttr,
} from "@/api/product/spu/type";
import {
  reqAllTrademark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddSpuOrUpdateSpu,
} from "@/api/product/spu";
import type { Trademark } from "@/api/product/trademark/type";
const emit = defineEmits(["changeScene"]);
import { useImaStore } from "@/store/modules/img";
const imgStore = useImaStore();
const uploadUrl = import.meta.env.VITE_BASE_API + "/admin/product/fileUpload";
// 点击取消按钮 通知父组件切换场景为0
const cancel = () => {
  emit("changeScene", { flag: 0 });
};

// 存储不完整的spu 即父组件传递的
const SpuParams = ref<any>({});

// 存储已有的spu数据
const AllTradeMark = ref<Trademark[]>([]);
// 存储商品图片
const imgList = ref<any>([]);
// 存储销售属性
const saleAttr = ref<SaleAttr[]>([]);
// 村塾销售属性值
const allSaleAttr = ref<HasSaleAttr[]>([]);
// 收集还未选择的销售属性的id和名字
const saleAttrIdAndName = ref<any>("");
const initHasSpuData = async (spu: SpuData) => {
  // 存储spu数据
  SpuParams.value = spu;
  console.log(SpuParams.value);

  // 获取所有的品牌数据
  const res: AllTradeMark = await reqAllTrademark();

  // 获取商品图片
  const resImg: SpuHasImg = await reqSpuImageList(spu.id as number);

  // 获取当前销售属性数据
  const resSaleAttr: SaleAttrResponseData = await reqSpuHasSaleAttr(
    spu.id as number
  );

  // 获取全部销售属性数据
  const resAllSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr();

  // 存储全部品牌的数据
  AllTradeMark.value = res.data;
  // 存储商品图片 修改key值 迎合ele Upload组件
  imgList.value = resImg.data.map((item) => {
    return { name: item.imgName, url: item.imgUrl };
  });
  // 存储当前销售属性
  saleAttr.value = resSaleAttr.data;
  console.log(saleAttr.value);

  // 存储全部销售属性
  allSaleAttr.value = resAllSaleAttr.data;
  console.log(allSaleAttr.value);
};

// 照片墙点击预览按钮时触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = !dialogVisible.value;
};

// 照片墙点击删除按钮时触发的钩子
const handleRemove = (file: any) => {
  console.log(file);
};

// 照片墙上传图片时触发的钩子 约束文件大小与类型
const handlerUpload = (file: File): boolean => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt4M = file.size / 1024 / 1024 < 4;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 PNG 或 JPG 格式！");
    return false;
  }

  if (!isLt4M) {
    ElMessage.error("上传图片大小不能超过 4MB！");
    return false;
  }

  return true;
};

// 控制照片预览对话框的显示与隐藏
const dialogVisible = ref(false);
// 存储照片预览的图片地址
const dialogImageUrl = ref("");

// 计算出当前SPU还未拥有的销售属性
const unSelectSaleAttr = computed(() => {
  // 全部的销售属性 : 颜色 版本 尺码
  const unSelectArr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName;
    });
  });
  return unSelectArr;
});

// 添加还未有的销售属性方法
const addSaleAttr = () => {
  console.log(saleAttrIdAndName.value);
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndName.value.split(":");
  // 准备新的销售属性对象
  const newSaleAttr: any = {
    baseSaleAttrId: Number(baseSaleAttrId),
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  // 追加到数组中
  saleAttr.value.push(newSaleAttr);
  // 清空收集的数据
  saleAttrIdAndName.value = "";
};

// 属性值按钮的点击回调
const toEdit = (row: any) => {
  // 点击按钮 input框显示->编辑模式
  row.flag = !row.flag;
  row.saleAttrValue = "";
};

// 属性值输入框失去焦点的回调
const toLook = (row: any) => {
  // 输入不可为空 或空格
  if (!row.saleAttrValue.trim()) {
    ElMessage.error("属性值不能为空");
    return;
  }

  // 防止收集输入值的数组不存在
  if (!row.spuSaleAttrValueList) {
    row.spuSaleAttrValueList = [];
  }
  // 属性值不可重复
  const repeat = row.spuSaleAttrValueList.find((item: any) => {
    return item.saleAttrValueName == row.saleAttrValue.trim();
  });
  if (repeat) {
    ElMessage.error("属性值不可重复");
    return;
  }
  // 整理收集的属性值id和属性值的名字
  const { baseSaleAttrId, saleAttrValue } = row;
  // 整理成服务器需要的属性值形式

  const newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue,
  };

  // 追加到数组当中
  row.spuSaleAttrValueList.push(newSaleAttrValue);

  // 切换为查看模式
  row.flag = !row.flag;
};

// 保存按钮的回调
const save = async () => {
  // 整理参数
  // 1.照片墙数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });

  // 把照片存到仓库中带给SKU
  imgStore.imgList = SpuParams.value.spuImageList;
  // 2.销售属性数据
  SpuParams.value.spuSaleAttrList = saleAttr.value;

  const res = await reqAddSpuOrUpdateSpu(SpuParams.value);
  console.log(res);

  if (res.code === 200) {
    ElMessage.success(SpuParams.value.id ? "修改成功" : "添加成功");
    emit("changeScene", {
      flag: 0,
      params: SpuParams.value.id ? "update" : "add",
    });
  } else {
    ElMessage.error(SpuParams.value.id ? "修改失败" : "添加失败");
  }
};

// 添加新的spu初始化请求方法
const initAddSpu = async (c3Id: number) => {
  console.log("添加新的spu初始化请求方法");

  // 清空表单数据
  SpuParams.value = {};
  // 清空照片墙
  imgList.value = [];
  // 清空销售属性
  saleAttr.value = [];

  // 存储三级id
  SpuParams.value.category3Id = c3Id;
  // 获取所有的品牌数据
  const res: AllTradeMark = await reqAllTrademark();
  // 获取全部销售属性数据
  const resAllSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr();

  // 存储数据
  AllTradeMark.value = res.data;
  allSaleAttr.value = resAllSaleAttr.data;
};
// 对外暴露
defineExpose({
  initHasSpuData,
  initAddSpu,
});
</script>

<style scoped></style>
